<?php
    require_ONCE("global.php");
    require_ONCE("db.php");
    
    if (!isset($_SESSION['user']))
    {
        header("Location:login.php");
        exit();
    }
    
    if (isset($_GET['cmd']))
    {
        $cmd = $_GET['cmd'];
        if ($cmd == "add")
        {
            $url = $_SERVER["HTTP_REFERER"];
            $userid = $_GET['userid'];
            $groupid = $_GET['groupid'];
            $sql = "insert into group_rel (groupid, userid) values (\"$groupid\", \"$userid\");";
            //var_dump($sql);
            $res = $db->query($sql);
            //var_dump($res);
            
            header("Location:$url");
            exit(0);
        }
        elseif ($cmd == "remove")
        {
            $url = $_SERVER["HTTP_REFERER"];
            $userid = $_GET['userid'];
            $groupid = $_GET['groupid'];
            $sql = "delete from group_rel where userid=$userid and groupid=$groupid";
            $res = $db->query($sql);
            //var_dump($res);
            header("Location:$url");
            exit(0);
        }
        
    }

    $userid = $_SESSION['user']["id"];
    // check user type
    $sql = "select * from users where userid = $userid and typeid = 2;";
    $res = $db->fetch_first($sql);
    if ($res == NULL)
    {
        echo "Not an admin account";
        //header("Location:index.php");
        exit();
    }
 
    $sql = "select * from users where userid=$userid;";
    $user = $db->fetch_first($sql);
    if ($user == NULL)
    {
        echo "can't get user info";
        exit();
    }
    
    $sql = "select * from company where id = ".$user["companyid"].";";
    $company = $db->fetch_first($sql);
    if ($user == NULL)
    {
        echo "can't get company info";
        exit();
    }



    if (isset($_GET['groupid']))
    {
        $groupid = $_GET['groupid'];
        
        $sql = "select * from users where userid=$groupid;";
        $group = $db->fetch_first($sql);
        if ($group['typeid'] != 3)
        {
            echo "input id is not a valid group id";
            exit();
        }
        
        $sql = "select * from users as u join group_rel as gr on u.userid = gr.userid where gr.groupid=$groupid;";
        $groupusers = $db->fetchAll($sql);
        
        $sql = "select * from users where companyid = ".$user['companyid']." and (typeid = 1 or typeid = 2) and userid NOT IN (select userid from group_rel where groupid = $groupid group by userid);";
        $users = $db->fetchAll($sql);
    }
    else
    {
        $sql = "select * from users where companyid = ".$user['companyid']." and typeid = 3;";
        $groups = $db->fetchAll($sql);

        $sql = "select * from users where companyid = ".$user['companyid']." and (typeid = 1 or typeid = 2);";
        $users = $db->fetchAll($sql);
    }
    
    include("templates/companyadmin.html");
?>